<template>
    <view>
        <!-- subpackage/payPage/payPage.wxml -->
        <custom-navbar :showTitle="false" backgroundColor="#ffffff" textColor="#ffffff" :showBack="true"
            :isCoverNav="false"></custom-navbar>
        <view class="payPage" :style="'height: calc(100vh - ' + navHeight + 'px - 172rpx);'">
            <!-- 顶部信息 -->
            <view class="top-info">
                <view class="price-section">
                    <text class="total-price">¥{{ totalAmount }}</text>
                    <text class="price-label">总金额</text>
                </view>
                <view class="order-type">
                    <text class="type-text">订单支付</text>
                </view>
            </view>
            <view class="payPage_form">
                <text class="payPage_form_title">请选择付款方式</text>
                <up-radio-group :value="radio" @change="onChange">
                    <up-cell clickable :data-name="item.id" @click="onClick($event, { name: item.id })"
                        :disabled="!item.enabled" v-for="(item, index) in paymentMethods" :key="index">
                        <view slot="title">
                            <view class="up-cell-text payment-method-item">
                                <image :src="item.icon" class="payment-icon" />
                                <text class="payment-name">{{ item.name }}</text>
                                <text v-if="!item.enabled" class="payment-disabled">暂不可用</text>
                            </view>
                        </view>

                        <up-radio slot="right-icon" :name="item.id" :disabled="!item.enabled" />
                    </up-cell>
                </up-radio-group>
            </view>
            <view class="payPage_footer">
                <view class="payPage_footer_info">
                    <view class="total-amount">
                        <text class="amount-label">实付金额</text>
                        <text class="amount-value">￥{{ totalAmount }}</text>
                    </view>
                </view>
                <view class="payPage_footer_btn">
                    <up-button color="rgba(57, 97, 54, 1)" round custom-class="btn" @tap.native="handlePayment"
                        :loading="paymentLoading" :disabled="paymentLoading" loading-text="支付中...">
                        {{ paymentLoading ? '支付中...' : '立即支付' }}
                    </up-button>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app'
import { ref, onMounted } from 'vue'
import customNavbar from '../../components/custom-navbar/index.vue'
import { payFun } from '@/api/port'





// 响应式数据
const navHeight = ref<number>(uni.getStorageSync('navHeight') ? uni.getStorageSync('navHeight') : 88)
const radio = ref<string>('1')
const orderInfo = ref<any>({})
const paymentLoading = ref<boolean>(false)
const paymentMethods = ref<any[]>([
    {
        id: '1',
        name: '微信支付',
        icon: 'https://image.shengxuankj.com/fronts/weChat.png',
        enabled: true
    }
])

// 总金额（从页面参数获取）
const totalAmount = ref(0)

// 方法定义
const showErrorAndGoBack = (message: string): void => {
    uni.showToast({
        title: message,
        icon: 'error',
        duration: 2000
    })
}

/**
 * 初始化页面数据
 * @param options 页面参数
 */
const initPageData = (options: any): void => {
    try {
        // 从页面参数获取总金额
        if (options.totalAmount) {
            totalAmount.value = parseFloat(options.totalAmount)
        }
        console.log('总金额:', totalAmount.value)
    } catch (error) {
        console.log('CatchClause', error)
        console.error('初始化页面数据失败:', error)
        showErrorAndGoBack('页面数据错误')
    }
}

const onClick = (event: any, _dataset?: any): void => {
    const name = event.currentTarget.dataset.name
    radio.value = name
}

const onChange = (event: any): void => {
    radio.value = event.detail
}

// 订单ID（从页面参数获取）
const order_id = ref<any>()

// 调用微信支付
const requestWeChatPay = async (orderInfo: any): Promise<any> => {
    try {
        // 这里应该调用后端API获取支付参数
        // 模拟获取支付参数
        const res = await payFun({ order_id: orderInfo.id, from: 'goods_order', pay_way: '2' })
        console.log('res', res)
        const paymentParams: any = {
            timeStamp: res.data.config.timeStamp,
            nonceStr: res.data.config.nonceStr,
            package: res.data.config.package,
            signType: res.data.config.signType,
            paySign: res.data.config.paySign
        }

        // 调用微信支付API
        return new Promise((resolve, reject) => {
            uni.requestPayment({
                ...paymentParams,
                success: (res: any) => {
                    console.log('支付成功:', res)
                    resolve(res)
                },
                fail: (err: any) => {
                    console.error('支付失败:', err)
                    if (err.errMsg === 'requestPayment:fail cancel') {
                        reject(new Error('用户取消支付'))
                    } else {
                        reject(new Error('支付失败: ' + err.errMsg))
                    }
                }
            })
        })
    } catch (error) {
        console.log('CatchClause', error)
        console.error('请求支付失败:', error)
        throw error
    }
}

// 处理支付流程
const handlePayment = async (): Promise<void> => {
    if (paymentLoading.value) {
        return
    }

    // 验证支付方式
    if (!radio.value) {
        uni.showToast({
            title: '请选择支付方式',
            icon: 'error'
        })
        return
    }

    // 验证订单信息
    if (!order_id.value || parseFloat(totalAmount.value) <= 0) {
        uni.showToast({
            title: '订单信息错误',
            icon: 'error'
        })
        return
    }

    paymentLoading.value = true

    try {
        const orderData = { id: order_id.value }
        
        // 根据支付方式处理支付
        if (radio.value === '1') {
            // 微信支付
            uni.showLoading({
                title: '正在调起支付...',
                mask: true
            })
            await requestWeChatPay(orderData)
            uni.hideLoading()

            // 支付成功，跳转到支付成功页面
            goToPayStatus(true, orderData)
        }
    } catch (error: any) {
        console.log('CatchClause', error)
        uni.hideLoading()
        let errorMessage = '支付失败'
        if (error.message === '用户取消支付') {
            errorMessage = '支付已取消'
        } else if (error.message) {
            errorMessage = error.message
        }
        uni.showToast({
            title: errorMessage,
            icon: 'error',
            duration: 2000
        })

        // 如果是支付失败（非用户取消），可以跳转到支付失败页面
        if (error.message !== '用户取消支付') {
            setTimeout(() => {
                goToPayStatus(false, null)
            }, 2000)
        }
    } finally {
        paymentLoading.value = false
    }
}

// 跳转到支付状态页面
const goToPayStatus = (success: boolean = true, orderData: any = null): void => {
    const params: any = {
        success: success ? '1' : '0',
        orderInfo: orderData?orderData:{}
    }
    // if (orderData) {
    //     params.orderInfo = encodeURIComponent(JSON.stringify(orderData))
    // }
    // const queryString = Object.keys(params)
    //     .map((key) => `${key}=${params[key]}`)
    //     .join('&')
    uni.navigateTo({
        url: `/subpackage/shopPayStatus/shopPayStatus?orderData=${encodeURIComponent(JSON.stringify(params))}`
    })
}
onLoad((options)=>{
    console.log(options)
    // 从页面参数获取订单ID
    if (options.orderId) {
        order_id.value = options.orderId
    }
    initPageData(options)
})
// 页面加载时处理
onMounted(() => {
    // 可以在这里处理页面参数
})

</script>
<style>
/* subpackage/payPage/payPage.wxss */
.payPage {
    width: 100%;
    background-color: rgba(245, 245, 245, 1);
    padding: 30rpx;
    box-sizing: border-box;
}

.top-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40rpx 30rpx;
    background: #fff;
    margin-bottom: 20rpx;
    border-radius: 10rpx;
}

.price-section {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.total-price {
    font-size: 48rpx;
    font-weight: bold;
    color: #ff6b35;
    margin-bottom: 5rpx;
}

.price-label {
    font-size: 24rpx;
    color: #999;
}

.order-type {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
}

.type-text {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 5rpx;
}

.items-text {
    font-size: 24rpx;
    color: #666;
}

/* .payPage_info text:nth-child(1) {
    font-size: 58rpx;
    font-weight: bolder;
    letter-spacing: 0px;
    line-height: 106.08rpx;
    color: rgba(19, 19, 19, 1);
} */

.payPage_info text:nth-child(2) {
    /** 文本1 */
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 40.54rpx;
    color: rgba(19, 19, 19, 1);
}

.payPage_info text:nth-child(3) {
    /** 文本1 */
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 40.54rpx;
    color: rgba(19, 19, 19, 1);
}

/* 日期信息样式 */
.payPage_info_dates {
    margin-top: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
}

.date-info {
    font-size: 24rpx;
    color: rgba(102, 102, 102, 1);
    line-height: 34rpx;
}

.nights-info {
    font-size: 22rpx;
    color: rgba(57, 97, 54, 1);
    background-color: rgba(57, 97, 54, 0.1);
    padding: 4rpx 12rpx;
    border-radius: 12rpx;
    line-height: 30rpx;
}



.payPage_form {
    width: 100%;
    margin-top: 30rpx;
    background-color: #fff;
    padding: 40rpx 0 20rpx 0;
    box-sizing: border-box;
    border-radius: 10rpx;
}

.payPage_form_title {
    width: 100%;
    padding: 0 30rpx;
    box-sizing: border-box;
    font-size: 33rpx;
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 20rpx;
}

.form-cell-group {
    margin: 0 !important;
}

/* 支付方式样式 */
.payment-method-item {
    display: flex;
    align-items: center;
}

.payment-icon {
    width: 36rpx;
    height: 36rpx;
    margin-right: 12rpx;
}

.payment-name {
    font-size: 30rpx;
    color: rgba(19, 19, 19, 1);
}

.payment-disabled {
    font-size: 24rpx;
    color: rgba(153, 153, 153, 1);
    margin-left: 12rpx;
}

.payPage_footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    min-height: 172rpx;
    padding: 24rpx 30rpx var(--safe-area-inset-bottom) 30rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    border-top: 1rpx solid rgba(238, 238, 238, 1);
}

.payPage_footer_info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
}

.total-amount {
    display: flex;
    align-items: center;
    gap: 16rpx;
}

.amount-label {
    font-size: 28rpx;
    color: rgba(102, 102, 102, 1);
}

.amount-value {
    font-size: 36rpx;
    font-weight: bold;
    color: rgba(57, 97, 54, 1);
}

.payPage_footer_btn {
    width: 100%;
    height: 80rpx;
    flex-shrink: 0;
}

.payPage_footer .btn {
    width: 100%;
    height: 100%;
    margin: 0 !important;
    font-size: 32rpx;
    font-weight: bold;
    transition: all 0.3s ease;
}

.payPage_footer .btn:active {
    transform: scale(0.98);
    opacity: 0.8;
}

/* 单选框样式 */
/* ⚠️ 直接覆盖 up-radio 的 icon 样式 */

/* 隐藏原图标（✓ 等） */

/* 选中状态的中心圆点 */
</style>
